package com.ssm.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ssm.pojo.Stu;
import com.ssm.service.StuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class StuDataListener extends AnalysisEventListener<Stu> {
    private static final Logger LOGGER = LoggerFactory.getLogger(StuDataListener.class);

    private static final int BATCH_COUNT = 10;

    List<Stu> list = new ArrayList<Stu>();
    private StuService stuService;

    public StuDataListener(StuService stuService) {
        this.stuService = stuService;
    }


    public void invoke(Stu stu, AnalysisContext analysisContext) {
        if (stu == null) {
            try {
                throw new Exception("文件数据为空");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (stu != null) {
            list.add(stu);
        }
        if (list.size() >= BATCH_COUNT) {
            LOGGER.info("{}条数据，开始存储数据库！", list.size());
            stuService.addStuList(list);
            LOGGER.info("存储数据库成功！");
            // 存储完成清理 list
            list.clear();
        }
    }

    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        stuService.addStuList(list);
        LOGGER.info("存储数据库成功！");
        LOGGER.info("所有数据解析完成！");
    }
}
